package com.jeeplus.modules.common.excel.common.validator.abs;

import com.jeeplus.common.utils.StringUtil;
import com.jeeplus.modules.common.excel.common.validator.chain.AbstractValidatorChain;

import java.lang.reflect.Field;

/**
 * 抽象类：字段校验器
 * @author wang.yishu
 * @date 2022.7.6
 */
public abstract class AbstractValidator {
    //所属的校验链
    protected AbstractValidatorChain chain;

    protected AbstractValidator next;

    public String getClassName () {
        return this.getClass().getName();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof AbstractValidator) {
            AbstractValidator validator = (AbstractValidator) obj;
            String className = validator.getClassName();
            return this.getClassName().equals(className);
        }
        return false;
    }

    /**
     * 检查是否可以校验该字段
     * @param field     字段属性
     * @return  boolean
     */
    public abstract boolean canValidate(Field field);

    /**
     * 执行校验
     * @param entity    对象
     * @param field     该对象的字段属性
     * @return          错误信息
     */
    public abstract String toValidate(Object entity, Field field);

    /**
     * 校验
     * @param entity     实体
     * @param field      字段
     * @return           错误信息
     */
    public String validate(Object entity, Field field, StringBuilder msg) {
        if (this.canValidate(field)) {
            String errMsg = this.toValidate(entity, field);
            if (StringUtil.isNotBlank(errMsg)) {
                msg.append(errMsg);
            }
        }
        if (this.next != null) {
            this.next.validate(entity, field, msg);
        }
        return msg.toString();
    }

    public AbstractValidator getNext() {
        return next;
    }

    public void setNext(AbstractValidator next) {
        this.next = next;
    }

    public AbstractValidatorChain getChain() {
        return chain;
    }

    public void setChain(AbstractValidatorChain chain) {
        this.chain = chain;
    }
}
